package com.ljm.sys.org.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljm.common.dto.UserInfoDto;
import com.ljm.common.enums.DataStatus;
import com.ljm.sys.org.api.SysOrgUserDepartApi;
import com.ljm.sys.org.entity.SysOrgUserDepart;
import com.ljm.sys.org.mapper.SysOrgUserDepartMapper;
import com.ljm.sys.org.service.ISysOrgUserDepartService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
    * 用户部门关联 服务实现类
    * </p>
 *
 * @author ming
 * @since 2019-04-22
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysOrgUserDepartServiceImpl extends ServiceImpl<SysOrgUserDepartMapper, SysOrgUserDepart>
        implements ISysOrgUserDepartService, SysOrgUserDepartApi {

    @Override
    public void userRefDept(List<Long> deptIds, Long userId, UserInfoDto curUser) {
        if(CollectionUtils.isEmpty(deptIds)){
            this.delByUserId(userId);
        }else{
            this.delByUserId(userId);
            List<SysOrgUserDepart> pos=new ArrayList<>();
            deptIds.forEach(deptId->{
                SysOrgUserDepart po=new SysOrgUserDepart();
                po.setCreateTime(LocalDateTime.now());
                po.setCreater(curUser.getLoginName());
                po.setStatus(DataStatus.NORMAL.getCode());
                po.setOrgId(curUser.getOrgId());
                po.setEditor(curUser.getLoginName());
                po.setEditTime(LocalDateTime.now());
                po.setDepartId(deptId);
                po.setUserId(userId);
                pos.add(po);
            });
            this.saveBatch(pos);
        }
    }

    @Override
    public void delByUserId(Long userId) {
        this.remove(new LambdaQueryWrapper<SysOrgUserDepart>().eq(SysOrgUserDepart::getUserId,userId));
    }

    @Override
    public List<Long> getRefDeptByUserId(Long userId) {
        List<Long> list=new ArrayList<>();
        List<SysOrgUserDepart> pos=this.list(new LambdaQueryWrapper<SysOrgUserDepart>().eq(SysOrgUserDepart::getUserId,userId));
        if(CollectionUtils.isNotEmpty(pos)){
            pos.forEach(po-> list.add(po.getDepartId()));
        }
        return list;
    }
}
